//
//  GAORefreshControl.swift
//  Weibo28
//
//  Created by 高辰 on 16/5/18.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

enum RefreshState: Int {
    //  下拉刷新
    case Normal = 0
    //  松手就刷新
    case Pulling = 1
    //  正在刷新
    case Refreshing = 2
    
}

//  当前刷新控件的高度
let RefreshControlH: CGFloat = 50

class GAORefreshControl: UIControl {
    //  当前滚动的视图
    var currentScrollView: UIScrollView?
    //  记录当前RefreshState状态
    var refreshState: RefreshState = RefreshState.Normal {
        didSet {
            switch refreshState {
            case .Normal:
                //  当上一个值是正在刷新状态时
                if oldValue == .Refreshing {
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.currentScrollView?.contentInset.top -= 50
                    })
                
                //停止状态指示动画
                indicatorView.stopAnimating()
                //显示箭头
                arrowImageView.hidden = false
                //重置箭头状态
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowImageView.transform = CGAffineTransformIdentity
                })
                messageLabel.text = "下拉刷新"
    
                }
            case .Pulling:
                 print("显示松手就刷新文本，箭头调转")
                messageLabel.text = "松手就刷新"
                //旋转箭头
                arrowImageView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                
                
            case .Refreshing:
                
                messageLabel.text = "正在刷新"
                //隐藏箭头
                arrowImageView.hidden = true
                //开启状态指示动画
                indicatorView.startAnimating()
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.currentScrollView?.contentInset.top += 50
                })
                
                sendActionsForControlEvents(.ValueChanged)
            }
            
        }
    }
    
    
    private lazy var messageLabel: UILabel = {
        let label = UILabel(textColor: UIColor.grayColor(), fontSize: 12)
        label.text = "下拉刷新"
        return label
    }()

    private lazy var arrowImageView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    //  指示控制器(正在刷新状态的图标)
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        addSubview(messageLabel)
        addSubview(arrowImageView)
        addSubview(indicatorView)
        
        //设置约束
        arrowImageView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self).offset(-35)
            make.centerY.equalTo(self)
        }
        indicatorView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowImageView)
        }
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(arrowImageView.snp_trailing)
            make.centerY.equalTo(self)
        }
        
    }
    
    //  将要添加到父视图时调用
    override func willMoveToSuperview(newSuperview: UIView?) {
        //  判断父视图能否强转为滚动视图
        if let scrollView = newSuperview as? UIScrollView {
            //  设置kvo监听滚动
            scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
            //  记录添加的滚动视图
            currentScrollView = scrollView
        }
        //  设置frame
        frame.size.width = ScreenWidth
        frame.size.height = RefreshControlH
        frame.origin.y = -RefreshControlH
    }
    
    //  kvo监听方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        //  拖动到刷新的临界点
        let maxY = -(currentScrollView!.contentInset.top + RefreshControlH)
        //  y轴偏移量
        let contentOffsetY = currentScrollView!.contentOffset.y
        
        if currentScrollView!.dragging {
            //  处于拖动时有两种状态: 提示下拉刷新状态 和 提示松手就刷新状态
            if contentOffsetY < maxY && refreshState == .Normal {
                // 大于临界点且处于提示下拉刷新状态时,处于提示松手就刷新状态
                refreshState = .Pulling
                print("Pulling")
            }else if contentOffsetY >= maxY && refreshState == .Pulling {
                // 处于提示下拉刷新状态
                refreshState = .Normal
                print("Normal")
            }
            
        }else {
            //  拖动过刷新的临界点时松手,才会进入正在刷新状态
            if refreshState == .Pulling {
                refreshState = .Refreshing
                print("Refreshing")
            }
        }
        
        
    }
    
    //  移除kvo
    deinit {
        currentScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    //停止刷新
    func endRefreshing() {
        refreshState = .Normal
    }
    
}
